/**
 * 
 */
package freedom.needle.sleep;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Vector;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author charlie
 *
 */
public class SleepWindow {

	protected final Logger logger = LoggerFactory.getLogger(getClass());
	private static final String pattern = "HH:mm:ss";
	SimpleDateFormat sdf = new SimpleDateFormat(pattern);

	private Calendar left;
	private Calendar right;
	private Vector<SleepWindowEventListener> listeners = new Vector<SleepWindowEventListener>();

	/**
	 * @param left
	 * @param right
	 */
	public SleepWindow(String left, String right) {
		super();
		this.left = Calendar.getInstance();
		this.right = Calendar.getInstance();
		try {
			this.left.setTime(sdf.parse(left));
			this.right.setTime(sdf.parse(right));
		} catch (ParseException e) {
			logger.error("SleepWindow ParseException", e);
		}
	}

	public void addListener(SleepWindowEventListener listener) {
		listeners.add(listener);
	}

	private void notifyListeners(SleepWindowEvent event) {
		Iterator<SleepWindowEventListener> iterator = listeners.iterator();
		while (iterator.hasNext()) {
			SleepWindowEventListener listener = iterator.next();
			listener.handleEvent(event);
		}
	}

	protected void open() {
		SleepWindowEvent sleepWindowEvent = new SleepWindowEvent(this, true);
		notifyListeners(sleepWindowEvent);
	}

	protected void close() {
		SleepWindowEvent sleepWindowEvent = new SleepWindowEvent(this, false);
		notifyListeners(sleepWindowEvent);
	}

	/**
	 * @return the left
	 */
	public Calendar getLeft() {
		return left;
	}

	/**
	 * @return the right
	 */
	public Calendar getRight() {
		return right;
	}

	/**
	 * @param listeners the listeners to set
	 */
	public void setListeners(Vector<SleepWindowEventListener> listeners) {
		this.listeners = listeners;
	}

}
